package com.salt.modules.sys.service;

import com.salt.common.service.TreeService;
import com.salt.core.redis.utils.CacheUtils;
import com.salt.modules.sys.entity.Admin;
import com.salt.modules.sys.entity.DataRule;
import com.salt.modules.sys.entity.Menu;
import com.salt.modules.sys.entity.User;
import com.salt.modules.sys.mapper.MenuMapper;
import com.salt.modules.sys.utils.AdminUtils;
import com.salt.modules.sys.utils.LogUtils;
import com.salt.modules.sys.utils.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单.
import java.util.Map;
 * @author salt
 * @version 2016-12-05
 */
@Service
@Transactional(readOnly = true)
public class MenuService extends TreeService<MenuMapper, Menu> {

    @Autowired
    private DataRuleService dataRuleService;

    public Menu get(String id) {
        return super.get(id);
    }

    public List<Menu> findAllMenu(Menu menu) {
        return UserUtils.getMenuList(menu);
    }

    /*public List<Menu> findAllMenu(Menu menu) {
        //return UserUtils.getMenuList(menu);
        User user = UserUtils.getUser();
        List<Menu> menuList = null;
        // 给开发人员添加管理员操作权限，待开发完成后删掉
        *//*String liXiaoId = "dd13928c8ada4ed8af0df2fe2ea8bba4"; // 李枭
        String zhangZhiYuan = "0540c5e7bf9a4c54b2b40852afeeae09"; //  张致远
        String zhaoYan = "f8956953eae849a9a58cadb85a4a403c";
        String chengfengfeng = "0adf19db75224a9aa3e502d1e21bfbb0";*//*
        //if (user.isAdmin() || liXiaoId.equals(user.getId()) || zhangZhiYuan.equals(user.getId()) || zhaoYan.equals(user.getId()) || chengfengfeng.equals(user.getId())){
            // 开发完成后，将上面删掉，将该行放开
        if (user.isAdmin() || AdminUtils.isAdmin(menu.getTenant())){
            //menuList = menuMapper.findAllList(new Menu());
            menuList = mapper.findAllList(menu);
        } else {
            menu.setUserId(user.getId());
            menuList = mapper.findByUserId(menu);
        }
        return menuList;
    }*/

    public List<Menu> getChildren(String parentId) {
        return super.getChildren(parentId);
    }

    //@LcnTransaction
    @Transactional(readOnly = false)
    public void saveMenu(Menu menu) {
        // 获取父节点实体
        menu.setParent(this.get(menu.getParent().getId()));
        // 获取修改前的parentIds，用于更新子节点的parentIds
        String oldParentIds = menu.getParentIds();
        // 设置新的父节点串
        menu.setParentIds(menu.getParent().getParentIds() + menu.getParent().getId() + ",");
        // 保存或更新实体
        super.save(menu);
        // 更新子节点 parentIds
        Menu m = new Menu();
        m.setParentIds("%," + menu.getId() + ",%");
        List<Menu> list = mapper.findByParentIdsLike(m);
        for (Menu e : list) {
            e.setParentIds(e.getParentIds().replace(oldParentIds, menu.getParentIds()));
            mapper.updateParentIds(e);
        }
        // 清除用户菜单缓存
        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        UserUtils.removeCache(UserUtils.CACHE_TOP_MENU);
        UserUtils.removeCache(UserUtils.CACHE_MENU_APP_LIST);
        // 清除日志相关缓存
        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
    }

    @Transactional(readOnly = false)
    public void updateSort(Menu menu) {
        mapper.updateSort(menu);
        // 清除用户菜单缓存
        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        UserUtils.removeCache(UserUtils.CACHE_TOP_MENU);
        // 清除日志相关缓存
        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
    }

    @Transactional(readOnly = false)
    public void delete(Menu menu) {
        // 解除菜单角色关联
        List<Map<String, Object>> mrlist = mapper.execSelectSql(
                "SELECT distinct a.menu_id as id FROM sys_role_menu a left join sys_menu menu on a.menu_id = menu.id WHERE a.menu_id ='"
                        + menu.getId() + "' OR menu.parent_ids LIKE  '%," + menu.getId() + ",%'");
        for (Map<String, Object> mr : mrlist) {
            mapper.deleteMenuRole(mr.get("id").toString());
        }
        // 删除菜单关联的数据权限数据，以及解除角色数据权限关联
        List<Map<String, Object>> mdlist = mapper.execSelectSql(
                "SELECT distinct a.id as id FROM sys_datarule a left join sys_menu menu on a.menu_id = menu.id WHERE a.menu_id ='"
                        + menu.getId() + "' OR menu.parent_ids LIKE  '%," + menu.getId() + ",%'");
        for (Map<String, Object> md : mdlist) {
            DataRule dataRule = new DataRule(md.get("id").toString());
            dataRuleService.delete(dataRule);
        }

        mapper.delete(menu);
        // 清除用户菜单缓存
        UserUtils.removeCache(UserUtils.CACHE_TOP_MENU);
        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        // 清除日志相关缓存
        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
    }


    public List<Menu> searchMenu(Menu menu) {
        List<String> tenantIds = menu.getTenantIds();
        String tenant = menu.getTenant();
        List<Menu> menuList = null;
        User user = UserUtils.getUser();
        if (user.isAdmin()){
            menuList = mapper.findAllList(menu);
        } else if (AdminUtils.isAdmin(tenant)) {
            List<Admin> adminList = AdminUtils.findAdminList(user);
            List<String> adminIds = new ArrayList<>();
            if (adminList != null && !adminList.isEmpty()) {
                adminList.stream().forEach(admin -> adminIds.add(admin.getTenant()));
            }
            if (!adminIds.isEmpty()) {
                List<String> adminTenantIdList = adminIds.stream().distinct().collect(Collectors.toList());
                menu.setTenant(null);
                menu.setTenantIds(adminTenantIdList);
                menuList = mapper.findAllList(menu); // 管理员
            }
            if (tenantIds != null && !tenantIds.isEmpty()) {
                if (!adminIds.isEmpty())
                    tenantIds = (List<String>) CollectionUtils.subtract(tenantIds, adminIds);
                if (!tenantIds.isEmpty()) {
                    menu.setTenant(null);
                    menu.setTenantIds(tenantIds);
                    menu.setUserId(user.getId());
                    List<Menu> menuListByUserId = mapper.findByUserId(menu); // 其它公司根据角色用户
                    menuList.addAll(menuListByUserId);
                }
            }
        } else {
            menu.setUserId(user.getId());
            menuList = mapper.findByUserId(menu);
        }
        return menuList;
    }
}
